package com.app.sysmodule.utils;

import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

public class AcewillBase64 {
    public final static String ENCODING = "UTF-8";

    /**
     * 数据BASE64加密字符?
     *
     * @param data           ：需要加密的字符?
     * @param additionSymbol ：加密干扰符
     * @return
     */
    public static byte[] encode(final String data, final String additionSymbol) {
        String finalData = data;
        if (!StringUtils.isBlank(additionSymbol)) {
            finalData = finalData + additionSymbol;
        }
        return Base64.encodeBase64(finalData.getBytes());
    }

    public static String stringEncode(final String data, final String additionSymbol) throws UnsupportedEncodingException {
        if (StringUtils.isBlank(data)) {
            return "";
        }
        return new String(encode(data, additionSymbol), ENCODING);
    }

    /**
     * 数据BASE64解码字符?
     *
     * @param data           :加密后的字符?
     * @param additionSymbol :干扰数据
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String decode(final String data, final String additionSymbol) throws UnsupportedEncodingException {
        if (StringUtils.isBlank(data)) {
            return "";
        }
        byte[] decodeString = Base64.decodeBase64(data.getBytes(ENCODING));
        if (!StringUtils.isBlank(additionSymbol)) {
            return new String(decodeString, ENCODING).replaceAll(additionSymbol, "");
        } else {
            return new String(decodeString, ENCODING);
        }
    }

    /**
     * BASE64解密
     *
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptBASE64(String key) throws Exception {
        return new Base64().decode(key.getBytes());
    }

    /**
     * BASE64加密
     *
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptBASE64(byte[] key) throws Exception {
        return new String(new Base64().encode(key));
    }

    //
    public static void main(String[] args) {
        try {
//			byte[] result = Base64.decodeBase64(s);
//			String s1 = new String(result);
//			System.out.println("789"+s1);
//			System.out.println(decode("=M2Y5ODVlZjBmMjI1MGUxMzhiZDQzODI4MmM3NTU0ZGQ2NjIxNTljYjEu5rWL6K+VMDEyLua1i+iv lTAyMy7mtYvor5UwMwo=","utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
